<template>
    <h3 style="margin: 10px 20px 0;">送货单</h3>
    <div class="search-box">
        <el-form :model="searchInfo" label-position="top">
            <div class="flex-container">
                <el-form-item label="客户名称">
                    <el-input 
                        v-model="searchInfo.clientName"
                        style="width: 220px;"
                    >
                    <template #prefix>
                        <el-icon><search /></el-icon>
                    </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="送货日期">
                    <el-date-picker
                        style="width: 220px;"
                        v-model="searchInfo.deliverDt"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        size="default"
                        value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <div style="margin-top: 10px;">
                    <el-button 
                        type="primary" icon="search" 
                        style="width: 80px;"
                        @click="handleSearch"
                    >
                        查询
                    </el-button>
                    <el-button 
                        icon="refresh" 
                        style="width: 80px;"
                        @click="handleReset"
                    >
                        重置
                    </el-button>
                </div>
            </div>
        </el-form>
    </div>
    <div class="btn-list">
        <div class="left-btns">
            <el-button 
                type="primary" 
                icon="plus" 
                style="width: 100px;margin-right: 6px;"
                @click="handleAdd"
            >
                添加
            </el-button>
            <el-button
                icon="delete" text
                :disabled="!deliveryIds.length"
                @click="handleDelete"
            >
                删除
            </el-button>
            <el-button
                :icon="Printer" text
                :disabled="!deliveryIds.length"
                @click="handlePrint"
            >
                打印
            </el-button>
            <el-button 
                icon="upload" text
                @click="handleExport"
            >
                导出
            </el-button>
            <el-button 
                icon="clock" text
                @click="handleLog"
            >
                历史记录
            </el-button>
            <el-button 
                icon="refresh" text
                @click="getTableData"
            >
                刷新
            </el-button>
        </div>
    </div>
    <div class="table-box">
        <el-table 
          ref="deliveryTableRef"
          :data="deliveryStore.deliveryList"
          style="width: 100%; height: 100%;"
          @selection-change="handleSelectionChange"
          @row-click="handleView"
          :default-sort="{ prop: 'deliverDt', order: 'descending' }"
          :header-cell-style="{ textAlign: 'center' }" 
          :cell-style="{ background: 'var(--el-table-tr-bg-color)', height:'80px', textAlign: 'center' }"
          v-loading="loading"
          element-loading-text="送货单数据加载中..."
          @sort-change="handleSortChange"
          border
        >
          <el-table-column prop="selection" type="selection" width="40" />
          <el-table-column prop="clientName" label="客户" width="120" fixed />
          <el-table-column prop="skuName" label="商品名称" width="120" />
          <el-table-column prop="skuBrand" label="商品牌号" width="100" />
          <el-table-column prop="internalBrand" label="内部牌号" width="100" />
          <el-table-column prop="specification" label="规格型号" width="140" />
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column sortable="custom" prop="shouldDeliver" label="应送" width="90" />
          <el-table-column sortable="custom" prop="oweDeliver" label="欠送" width="90" />
          <!-- <el-table-column prop="inventory" label="库存量" width="90" sortable /> -->
          <el-table-column sortable="custom" prop="thisDeliver" label="本次送" width="90">
            <template #default="scope">
                <el-tag type="success" size="large" style="font-weight: 600; width: 100%;">{{ scope.row.thisDeliver }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="checked" label="审核状态" width="90" >
            <template #default="scope">
              <el-tag
                :type="handleCheckedColor(scope.row.checked)"
              >
                {{ handleCheckedText(scope.row.checked) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column sortable="custom" prop="deliverDt" label="送货日期" width="130" />
          <el-table-column prop="thisDeliverAmount" label="本次送金额" width="110" />
          <el-table-column prop="thisDeliverWeight" label="本次送重量" width="110" />
          <!-- <el-table-column prop="clientCode" label="客户代号" width="100" /> -->
          <el-table-column prop="orderId" label="订单号" width="130" show-overflow-tooltip />
          <!-- <el-table-column prop="operation" label="操作" width="80" fixed="right" align="center">
            <template #default="scope">
              <el-button type="primary" plain size="small" @click.native.stop="handleEdit(scope.row)">编辑</el-button>
            </template>
          </el-table-column> -->
        </el-table>
    </div>
    <div class="pagination-box">
        <el-pagination 
            layout="sizes, prev, pager, next" 
            :total="searchInfo.total"
            v-model:current-page="searchInfo.pageNum"
            v-model:page-size="searchInfo.pageSize"
            :page-sizes="[5, 10, 30, 50]"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
    </div>
    <!-- <ViewDialog v-model="viewVisible" /> -->
    <logDialog v-model="logVisible" ref="logRef" logType="送货单管理" />
    <EditDialog v-model="editVisible" :deliveryType="deliveryType" :getTableData="getTableData" ref="editDialogRef"/>
</template>

<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import { useDeliveryStore } from '@/stores/sale/delivery'
import ViewDialog from '@/pages/home/views/sale/delivery/components/viewDialog.vue'
import EditDialog from '@/pages/home/views/sale/delivery/components/editDialog.vue'
import { Printer } from '@element-plus/icons-vue'
import { getDeliveryList, exportDelivery, deleteDelivery } from '@/pages/home/views/sale/api/delivery'
import logDialog from '@/pages/home/views/sale/order/components/logDialog.vue'
import { dragTable } from '@/pages/home/views/sale/utils/dragTable'
import { transformRMB } from '@/pages/home/views/sale/utils/base'
import { ElMessage } from 'element-plus'

const searchInfo = ref({
  clientName: "",
  deliverDt: "",
  pageNum: 1,
  pageSize: 30,
  total: 0,
  sortBy: "deliver_dt",
  sort: "desc"
})
const deliveryIds = ref([])
const viewVisible = ref(false)
const editVisible = ref(false)
const deliveryType = ref("view")
const logVisible = ref(false)
const logRef = ref()
const deliveryTableRef = ref()
const deliveryStore = useDeliveryStore()
const loading = ref(true)
const editDialogRef = ref()

const handleSearch = async () => {
    getTableData()
}
const handleReset = () => {
    searchInfo.value.clientName = ""
    searchInfo.value.deliverDt = ""
}
const handleAdd = () => {
    deliveryType.value = 'add'
    editVisible.value = true
    editDialogRef.value.handleSelectOrder()
    getCurrentDeliveryDateTime()
}
const handleDelete = async () => {
    let ids = deliveryIds.value.join(",")
    const res = await deleteDelivery({ noList: ids })
    console.log("delete res:", res.data)
    getTableData()
}
const handleExport = async () => {
    const res = await exportDelivery({
        clientName: searchInfo.value.clientName,
        deliverDtFrom: searchInfo.value.deliverDt?.[0] ?? "",
        deliverDtTo: searchInfo.value.deliverDt?.[1] ?? "",
        pageNum: searchInfo.value.pageNum,
        pageSize: searchInfo.value.pageSize
    })
    const blob = new Blob(
      [res.data],
      { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }
    )
    const url = URL.createObjectURL(blob)
    const a = document.createElement("a")
    a.href = url
    a.download = "送货单.xlsx"
    a.click()
    URL.revokeObjectURL(url)
}
const handleLog = async () => {
    logVisible.value = true
    logRef.value.getLogTableData()
}
const handleSelectionChange = (rows) => {
    deliveryIds.value = rows.map(row => row.no)
    console.log("deliveryIds", deliveryIds.value)
}
const handleView = (row) => {
    // deliveryType.value = 'view'
    // viewVisible.value = true
    // deliveryStore.delivery = { ...row }
}
const handleEdit = async (row) => {
    deliveryType.value = 'edit'
    editVisible.value = true
    console.log(deliveryStore.delivery)
    await nextTick()
    deliveryStore.delivery = { ...row }
    console.log(deliveryStore.delivery)
}
const handlePrint = () => {
    let cssStyle = document.createElement("style"); 
    cssStyle.innerHTML = `
        .container {
            width: 100%;
            height: 1000px;
        }
        .print {
            width: 600px;
            height: 350px;
            border: 1px black solid;
            background-color: #d9d9d9;
            -webkit-print-color-adjust: exact;
            padding: 10px;
            margin-bottom: 10px;
        }
        .title {
            font-size: 32px;
            font-weight: bold;
            display: flex;
            flex-direction: column;
            row-gap: 10px;
            align-items: center;
        }
        .desc { font-weight: 500; }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 30px;
        }
        @page {
            margin: 10px;
        }`;
    const printContentHtml = `
    <div class="container">
        <div class="title">
            <span style="color: #f5222d; -webkit-print-color-adjust: exact;">制造业小微企业</span>
            <span>送货单</span>
        </div>
        ${deliveryStore.deliveryList
            .filter(item => deliveryIds.value.includes(item.no))
            .map(delivery => `
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <div style="width: 220px; text-align: left;">客户名称: ${delivery.clientName}</div>
                    <div style="width: 220px; text-align: center;">客户代号: ${delivery.clientCode}</div>
                    <div style="width: 220px; text-align: right;">订单号: ${delivery.orderId}</div>
                </div>
                <table cellspacing="0" cellpadding="1" border="1">
                    <thead>
                        <tr>
                            <th style="width: 50px;">单号</th>
                            <th style="width: 120px;">商品</th>
                            <th style="width: 100px;">商品牌号</th>
                            <th style="width: 100px;">内部牌号</th>
                            <th style="width: 140px;">规格型号</th>
                            <th style="width: 70px;">单位</th>
                            <th style="width: 100px;">应送</th>
                            <th style="width: 100px;">欠送</th>
                            <th style="width: 100px;">本次送</th>
                            <th>送货日期</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td style="text-align: center;">${delivery.no}</td>
                            <td style="text-align: center;">${delivery.skuName}</td>
                            <td style="text-align: center;">${delivery.skuBrand}</td>
                            <td style="text-align: center;">${delivery.internalBrand}</td>
                            <td style="text-align: center;">${delivery.specification}</td>
                            <td style="text-align: center;">${delivery.unit}</td>
                            <td style="text-align: center;">${delivery.shouldDeliver}</td>
                            <td style="text-align: center;">${delivery.oweDeliver}</td>
                            <td style="text-align: center;">${delivery.thisDeliver}</td>
                            <td style="text-align: center;">${delivery.deliverDt}</td>
                        </tr>
                    </tbody>
                </table>
                <div style="display: flex; justify-content: space-between; align-items: center; margin: -20px 0 30px;">
                    <div>金额：${delivery.thisDeliverAmount ?? "暂无金额"}</div>
                    <div>金额（大写）：${transformRMB(delivery.thisDeliverAmount)}</div>
                    <div>收货方签字：____________________</div>
                </div>
            `).join('')}
    </div>`
    const iframe = document.createElement("iframe");
    iframe.setAttribute(
        "style",
        "position:absolute;width:0px;height:0px;left:-50px;top:-50px;"
    );
    document.body.appendChild(iframe)
    iframe.contentDocument.getElementsByTagName("head")[0].appendChild(cssStyle);
    iframe.contentDocument.body.innerHTML = "<div>" + printContentHtml + "</div>"
    iframe.contentDocument.close();
    iframe.contentWindow.focus();
    iframe.contentWindow.print();
    document.body.removeChild(iframe);
}
const handleCurrentChange = (val) => {
    searchInfo.value.pageNum = val
    getTableData()
}

const handleSizeChange = (val) => {
    searchInfo.value.pageSize = val
    getTableData()
}

const handleCheckedColor = (row) => {
  switch (row) {
    case 1:
      return "success"
    case 0:
      return "warning"
    case 2:
      return "danger"
  }
}

const handleCheckedText = (row) => {
  switch (row) {
    case 0:
      return "待审核"
    case 1:
      return "已通过"
    case 2:
      return "不通过"
  }
}

const handleSortChange = ({column, prop, order }) => {
    const DELIVERY_SORT_DB = {
      shouldDeliver: "should_deliver",
      oweDeliver: "owe_deliver",
      thisDeliver: "this_deliver",
      deliverDt: "deliver_dt"
    };
    searchInfo.value.sortBy = DELIVERY_SORT_DB[prop]
    searchInfo.value.sort = order === "ascending" ? "asc" : order === "descending" ? "desc" : null
    getTableData()
}

const getTableData = async () => {
    loading.value = true
    try {
        const deliveryData = await getDeliveryList({
            clientName: searchInfo.value.clientName,
            deliverDtFrom: searchInfo.value.deliverDt?.[0] ?? "",
            deliverDtTo: searchInfo.value.deliverDt?.[1] ?? "",
            pageNum: searchInfo.value.pageNum,
            pageSize: searchInfo.value.pageSize,
            sortBy: searchInfo.value.sortBy,
            sort: searchInfo.value.sort
        })
        if(deliveryData.data.success === false) {
            throw new Error(deliveryData.data.errorMsg)
        }
        console.log("deliveryData.data", deliveryData.data)
        deliveryStore.deliveryList = deliveryData.data.data.list
        searchInfo.value.total = deliveryData.data.data.total
        loading.value = false
    }
    catch (error) {
        ElMessage.error(error.message || "调用接口异常")
        loading.value = false
    }   
}

function getCurrentDeliveryDateTime () {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')
    
    deliveryStore.delivery.deliverDt = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

onMounted(() => {
    dragTable(deliveryTableRef)
    getTableData()
})

</script>

<style scoped>
.search-box {
    margin: 10px 20px;
}
.flex-container {
    display: flex;
    flex-flow: row wrap;
    gap: 12px;
    align-items: flex-end;
}
.el-form-item {
    margin-bottom: 0;
}
.btn-list {
    border: 1px solid #e1e3e5;
    border-bottom: none;
    border-radius: 4px 4px 0 0;
    margin: 0 20px;
    padding: 6px 12px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    overflow: hidden;
}
.left-btns {
    display: flex;
    align-items: center;
}
.el-button.is-text {
    padding: 0 6px;
    margin: 0;
}
.table-box{
    flex: 1;
    overflow-y: auto;
    margin: 0 20px;
    border: none;
}
.el-table {
    --el-table-header-bg-color: var(--el-bg-color-page);
    --el-table-border-color: var(--el-border-color-dark);
    --el-table-header-text-color: var(--el-text-color-primary);
}
:deep(.caret-wrapper){
    width: 0;
}
.pagination-box {
    margin: 10px 20px;
    display: flex;
    justify-content: flex-end;
}

:deep(th.el-table__cell){
  border-bottom: var(--el-table-border) !important;
}
:deep(.el-table-fixed-column--left){
  outline: var(--el-table-border);
  border: none !important;
}
:deep(.el-table-fixed-column--right){
  outline: var(--el-table-border);
  border: none !important;
}
</style>